#!/usr/bin/python2.6

# no option needed, so comment it out
#from optparse import OptionParser
from errno import EINVAL
from sys import exit, argv
from os.path import basename
from urllib import urlencode
from urllib2 import urlopen
from conf import URL_VS, BG_AI_URL, BG_AT_URL
from const import BUILD_TYPE_DT, BUILD_TYPE_OS
from genbldlst import gen_bldlst

def usage():
    print """
usage:  %s  cmd  args

  cmd:
       ai  <os_rel> <dt|os> <bno>   
       at  <jids, e.g. 1,2,3,4>
""" % basename(argv[0])


if __name__ == '__main__':
    anum = len(argv)

    arg_check_flag = False
    build_type = None
    if anum > 1:
        if argv[1] == 'ai' and anum == 5:
            if argv[3] == 'dt':
                arg_check_flag = True
                build_type = BUILD_TYPE_DT
            elif argv[3] == 'os':
                arg_check_flag = True
                build_type = BUILD_TYPE_OS
                # update os build list
                gen_bldlst()
        elif argv[1] == 'at' and anum == 3:
            # check if job id is digit
            try:
                jids = map(int, argv[2].split(URL_VS))
            except Exception:
                #FIXME: list specific exception here
                pass
            else:
                arg_check_flag = True

    if not arg_check_flag:
        usage()
        exit(EINVAL)

    url = None
    post_date = None
    if argv[1] == 'ai':
        url = BG_AI_URL
        post_data = urlencode({'r': argv[2],
                               't': build_type,
                               'b': argv[4]})
    elif argv[1] == 'at':
        url = BG_AI_URL
        post_data = urlencode({'jid': argv[2]})

    response = urlopen(url, post_data).read()
    print response
